package com.yiqi.news.mvp.ui.activity

import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import butterknife.OnClick
import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.jess.arms.widget.DividerItemDecoration
import com.yiqi.huize.dp2px
import com.yiqi.huize.isVisible
import com.yiqi.huize.mvp.dialog.OpenPageDialog
import com.yiqi.huize.setOnTextChanged
import com.yiqi.news.R
import com.yiqi.news.app.utils.SearchUtil
import com.yiqi.news.di.component.DaggerSearchComponent
import com.yiqi.news.di.module.SearchModule
import com.yiqi.news.entity.HotVO
import com.yiqi.news.entity.News
import com.yiqi.news.mvp.contract.SearchContract
import com.yiqi.news.mvp.presenter.SearchPresenter
import com.yiqi.news.mvp.ui.adapter.NewsAdapter
import com.yiqi.news.mvp.ui.adapter.SearchHistoryAdapter
import com.yiqi.news.mvp.ui.adapter.SearchHotAdapter
import kotlinx.android.synthetic.main.activity_search.*


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/20/2019 10:21
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
/**
 * 如果没presenter
 * 你可以这样写
 *
 * @ActivityScope(請注意命名空間) class NullObjectPresenterByActivity
 * @Inject constructor() : IPresenter {
 * override fun onStart() {
 * }
 *
 * override fun onDestroy() {
 * }
 * }
 */
class SearchActivity : BaseActivity<SearchPresenter>(), SearchContract.View, TextView.OnEditorActionListener, OpenPageDialog.OnClickListener {

    override fun onOpen() {
        SearchUtil.clearHistory()
        mHistoryAdapter.setNewData(null)
    }

    private var mPageIndex: Int = 2
    private val mPageSize: Int = 20

    private val mAdapter: NewsAdapter by lazy {
        return@lazy NewsAdapter()
    }

    private val mOpenPageDialog by lazy {
        return@lazy OpenPageDialog(this)
    }

    override fun showHotData(hot: List<HotVO>) {
        mHotAdapter.setNewData(hot)
    }

    override fun showHistoryData(history: List<String>) {
        mHistoryAdapter.setNewData(history)
    }

    private val mHistoryAdapter: SearchHistoryAdapter by lazy {
        return@lazy SearchHistoryAdapter()
    }

    private val mHotAdapter: SearchHotAdapter by lazy {
        return@lazy SearchHotAdapter()
    }


    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerSearchComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .searchModule(SearchModule(this))
                .build()
                .inject(this)
    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_search //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    override fun initData(savedInstanceState: Bundle?) {
        initAdapter()
        mPresenter?.getHotData()
        edt_news_search.setOnTextChanged { s, start, before, count ->
            ll_search.isVisible(s!!.isEmpty())
            rv_search_result.isVisible(s!!.isNotEmpty())

        }
    }


    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {

            if (edt_news_search.text.isNullOrEmpty()) {
                showMessage("请输入搜索关键词")
            } else {
                ArmsUtils.hidekeyboard(this)
                SearchUtil.saveSearchHistory(edt_news_search.text.toString().trim())
                mPresenter?.getNewsData(1, mPageSize, edt_news_search.text.toString().trim())
            }

            return true
        }
        return false
    }

    override fun showNewsData(data: List<News>, tips: String) {
        ll_search.isVisible(data.isEmpty())
        rv_search_result.isVisible(data.isNotEmpty())
        mAdapter.setNewData(data)
        if (data.size < mPageSize) {
            mAdapter.loadMoreEnd()
        }
    }


    override fun showNewsError(msg: String) {
        mAdapter.loadMoreFail()
    }

    override fun showEmpty(isRefresh: Boolean) {
        ArmsUtils.snackbarText("暂无数据")
        mAdapter.setNewData(null)
//        if (isRefresh){
//            mAdapter.setEnableLoadMore(false)
//        }
//        mAdapter.loadMoreEnd(isRefresh)
    }

    override fun showNewsMore(string: List<News>, tips: String) {
        setData(string)
    }

    private fun setData(data: List<News>?) {
        mPageIndex++
        val size = data?.size ?: 0

        if (size > 0) {
            mAdapter.addData(data!!)
        }

        if (size < mPageSize) {
            mAdapter.loadMoreEnd(false)
        } else {
            mAdapter.loadMoreComplete()
        }
    }

    override fun showNewsMoreError(msg: String) {

    }

    override fun initEvent() {
        edt_news_search.setOnEditorActionListener(this)
    }

    override fun showMessage(message: String) {
        ArmsUtils.snackbarText(message)
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(tool_search).init()
    }

    private fun initAdapter() {


        rv_search_hot.layoutManager = GridLayoutManager(this, 3)
        rv_search_history.layoutManager = GridLayoutManager(this, 5)
        mHotAdapter.bindToRecyclerView(rv_search_hot)
        mHistoryAdapter.bindToRecyclerView(rv_search_history)
        mHotAdapter.setOnItemClickListener { _, _, position ->
            edt_news_search.setText(mHotAdapter.getItem(position)?.hotKey)
            mHotAdapter.getItem(position)?.hotKey?.let { mPresenter?.getNewsData(1, mPageSize, it) }
        }
        mHistoryAdapter.setOnItemClickListener { _, _, position ->
            edt_news_search.setText(mHistoryAdapter.getItem(position))
            mHistoryAdapter.getItem(position)?.let { mPresenter?.getNewsData(1, mPageSize, it) }
        }
        rv_search_result.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(3)))
        rv_search_result.adapter = mAdapter
        mAdapter.setOnLoadMoreListener({
            loadMore()
        }, rv_search_result)
    }

    private fun loadMore() {
        mPresenter?.getNewsDataMore(mPageIndex, mPageSize, edt_news_search.text.toString().trim())
    }


    @OnClick(R.id.btn_search_clear, R.id.btn_search_back)
    fun onClick(view: View) {
        when (view.id) {
            R.id.btn_search_clear -> {
                mOpenPageDialog.setDesc("是否清空历史记录")
                mOpenPageDialog.setOnClickListener(this)
                mOpenPageDialog.show()
            }
            R.id.btn_search_back -> finish()
        }
    }

}
